package com.fjwt.gz.service.impl;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fjwt.gz.core.cache.RedisUtil;
import com.fjwt.gz.core.constants.Constants;
import com.fjwt.gz.db.dto.InviterRecordDTO;
import com.fjwt.gz.db.entity.AgentScoreRuleEntity;
import com.fjwt.gz.db.entity.FansEntity;
import com.fjwt.gz.db.entity.FansUserEntity;
import com.fjwt.gz.db.entity.InviterRecordEntity;
import com.fjwt.gz.db.vo.InviterRecordVO;
import com.fjwt.gz.service.mapper.InviterRecordMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * <p>
 * 邀请记录表(注册小程序奖励福分) 服务实现类
 * </p>
 *
 * @author shiyonghao
 * @since 2025-04-09
 */
@Slf4j
@Service
public class InviterRecordService extends ServiceImpl<InviterRecordMapper, InviterRecordEntity> {

    @Autowired
    private InviterRecordService inviterRecordService;
    @Autowired
    private FansService fansService;
    @Autowired
    private FansUserService fansUserService;
    @Autowired
    private AgentScoreRuleService agentScoreRuleService;
    @Autowired
    private ScoreRecordTotalService scoreRecordTotalService;

    /**
     * 福分拉新记录
     * @return
     */
    public IPage<InviterRecordVO> findUserInviterList(IPage iPage, Long fansId) {
        return baseMapper.findUserInviterList(iPage,fansId);
    }

    /**
     * 分页获取邀请记录
     * @param page
     * @return
     */
    public IPage<InviterRecordDTO> queryInviterRecord(Page page) {
        return baseMapper.queryInviterRecord(page);
    }

    public int inviterConfirmAward(Long inviterId, Long userId, String officialAppId, String time, String appId) {
        LambdaQueryWrapper<AgentScoreRuleEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AgentScoreRuleEntity::getRuleKey, Constants.POINT.INVITER_KEY);
        AgentScoreRuleEntity ruleEntity = agentScoreRuleService.getBaseMapper().selectOne(queryWrapper);
        int i = 0;
        log.info("接受邀请信息发起方人id：{}，接收方id：{}，公众号：{}",inviterId,userId,officialAppId);
        FansUserEntity userEntity = fansUserService.getById(userId);
        log.info("客户地域小程序信息：{}", JSONObject.toJSONString(userEntity));
        if(null == userEntity){
            return 5;
        }
        FansEntity fansEntity = fansService.getById(userEntity.getFansId());
        String inviteTimeKey = "inviteTime:" + userEntity.getFansId();
        if (RedisUtil.hasKey(inviteTimeKey)){
            time = RedisUtil.getString(inviteTimeKey);
        }
        if(userEntity.getCreatedAt().before(DateUtil.parse(time))){
            return 1;
        }
        // 查询新用户是否存在被邀约记录
        LambdaQueryWrapper<InviterRecordEntity> inviterRecordQueryWrapper = new LambdaQueryWrapper<>();
        inviterRecordQueryWrapper.eq(InviterRecordEntity::getInvitedFansId, fansEntity.getFansId());
        inviterRecordQueryWrapper.eq(InviterRecordEntity::getIsSuccess, 1);
        InviterRecordEntity inviterRecordEntity = inviterRecordService.getOne(inviterRecordQueryWrapper);
        if (ObjectUtils.isNotEmpty(inviterRecordEntity)){
            return 1;
        }
        LambdaQueryWrapper<FansUserEntity> userMsgQueryWrapper = new LambdaQueryWrapper();
        userMsgQueryWrapper.eq(FansUserEntity::getFansId,userEntity.getFansId());
        userMsgQueryWrapper.eq(FansUserEntity::getType, 0);//地域公众号
        userMsgQueryWrapper.eq(FansUserEntity::getAppId,officialAppId);
        FansUserEntity userMsgEntity = fansUserService.getOne(userMsgQueryWrapper);
        if(null == userMsgEntity){
            RedisUtil.setString(inviteTimeKey, time);
            return 3;
        }
        LambdaQueryWrapper<FansUserEntity> entityQueryWrapper = new LambdaQueryWrapper();
        entityQueryWrapper.eq(FansUserEntity::getFansId, inviterId);
        entityQueryWrapper.eq(FansUserEntity::getType, 1);//小程序
        FansUserEntity entity = fansUserService.getOne(entityQueryWrapper);
        log.info("发起邀请方用户信息：{}",JSONObject.toJSONString(entity));
        if(null == entity){
            return 4;
        }
        InviterRecordEntity dto = new InviterRecordEntity();
        dto.setFansId(inviterId);
        dto.setInvitedFansId(fansEntity.getFansId());
        dto.setAppId(appId);
        dto.setCreatedAt(new Date());
        Integer isFollow = userMsgEntity.getIsFollow();
        if(StringUtils.isEmpty(fansEntity.getPhone())){
            i = 6;
        }else{
            if(0 == isFollow){
                dto.setIsFollow(1);
                int generate = scoreRecordTotalService.scoreRecordGenerate(inviterId, ruleEntity.getScoreRuleId(), "邀请新人获得福分", Constants.SCORE.RULE, null, appId);
                if(generate > 0 ){
                    dto.setIsSuccess(1);
                }
            }else{
                i =  2;
            }
        }
        inviterRecordService.save(dto);
        RedisUtil.del(inviteTimeKey);
        return i;
    }
}
